import createAxiosClient from "@/app/utils/axiosRequest";
import {decodeFromBase64, encodeToBase64} from "next/dist/build/webpack/loaders/utils";
import cookie from "react-cookies";
import {UserName} from "@/app/constants/authTokenConstants";
import {Simulate} from "react-dom/test-utils";
import ToastUtil from "@/app/utils/toastUtil";

/**
 * 笔记模型
 */
export interface NoteItem {
  id: number;
  collectionId: number;
  collectionName?: string;
  userId: number;
  userName?: string;
  title: string;
  content: string;
  icon?: string;
  emoji?: string;
  version?: number;
  isPublic: number;
  viewCount?: number;
  tags?: {
    id: number;
    name: string;
    userId: number;
    createdAt?: string;
    updatedAt?: string;
  }[];
  createdAt?: string;
  updatedAt?: string;
}

/**
 * 笔记列表响应
 */
export interface NoteListResponse {
  records: NoteItem[];
  total: number;
  size: number;
  current: number;
  pages: number;
}

/**
 * 获取笔记列表
 * @param collectionId 文件夹/集合ID，传null获取根目录
 * @param current 当前页码
 * @param size 每页条数
 * @returns 笔记列表数据
 */
export default async function NoteService(collectionId: string | null, current: number = 1, size: number = 100): Promise<any> {
  // 获取请求实例
  const axiosInstance = createAxiosClient();
  
  // 处理collectionId: 转换"root"或"/"为null，其他情况使用原值或转数字
  const processedCollectionId = collectionId === "root" || collectionId === "/" ? null : 
                             collectionId ? parseInt(collectionId) : null;
  
  try {
    // 调用新API
    const response = await axiosInstance.get("/app/api/v1/notes/user", {
      params: {
        "collectionId": processedCollectionId,
        "current": current,
        "size": size
      }
    });
    
    const data = response.data;
    console.log("API返回的笔记数据:", JSON.stringify(data, null, 2));
    
    // 直接返回完整响应，让渲染组件处理
    return data;
  } catch (error: any) {
    ToastUtil(error.message || "获取笔记列表异常", "❌", "error");
    return { status: false, message: error.message, data: { records: [], total: 0, size, current, pages: 0 } };
  }
}

/**
 * 获取笔记详情
 * @param noteId 笔记ID
 * @returns 笔记详情
 */
export async function getNoteDetail(noteId: number): Promise<NoteItem | null> {
  // 获取请求实例
  const axiosInstance = createAxiosClient();
  
  try {
    const response = await axiosInstance.get(`/app/api/v1/notes/${noteId}`);
    
    const data = response.data;
    if (data.status) {
      return data.data;
    } else {
      ToastUtil(data.message || "获取笔记详情失败", "❌", "error");
      return null;
    }
  } catch (error: any) {
    ToastUtil(error.message || "获取笔记详情异常", "❌", "error");
    return null;
  }
}

/**
 * 创建笔记参数
 */
export interface CreateNoteParams {
  collectionId: number;
  title: string;
  content: string;
  tagIds?: { id: number }[];
  isPublic?: number;
  emoji?: string;
  icon?: string;
}

/**
 * 创建笔记
 * @param params 创建笔记参数
 * @returns 是否成功
 */
export async function createNote(params: CreateNoteParams): Promise<{ success: boolean; noteId?: number }> {
  // 获取请求实例
  const axiosInstance = createAxiosClient();
  
  try {
    const response = await axiosInstance.post("/app/api/v1/notes", params);
    
    const data = response.data;
    if (data.status) {
      ToastUtil(data.message || "创建笔记成功", "✅", "success");
      return { success: true, noteId: data.data?.id };
    } else {
      ToastUtil(data.message || "创建笔记失败", "❌", "error");
      return { success: false };
    }
  } catch (error: any) {
    ToastUtil(error.message || "创建笔记异常", "❌", "error");
    return { success: false };
  }
}

/**
 * 更新笔记参数
 */
export interface UpdateNoteParams {
  id: number;
  collectionId?: number;
  title?: string;
  content?: string;
  tagIds?: { id: number }[];
  isPublic?: number;
  emoji?: string;
  icon?: string;
}

/**
 * 更新笔记
 * @param params 更新笔记参数
 * @returns 是否成功
 */
export async function updateNote(params: UpdateNoteParams): Promise<boolean> {
  // 获取请求实例
  const axiosInstance = createAxiosClient();
  
  try {
    const response = await axiosInstance.put("/app/api/v1/notes", params);
    
    const data = response.data;
    if (data.status) {
      ToastUtil(data.message || "更新笔记成功", "✅", "success");
      return true;
    } else {
      ToastUtil(data.message || "更新笔记失败", "❌", "error");
      return false;
    }
  } catch (error: any) {
    ToastUtil(error.message || "更新笔记异常", "❌", "error");
    return false;
  }
}

/**
 * 删除笔记
 * @param noteId 笔记ID
 * @returns 是否成功
 */
export async function deleteNote(noteId: number): Promise<boolean> {
  // 获取请求实例
  const axiosInstance = createAxiosClient();
  
  try {
    const response = await axiosInstance.delete(`/app/api/v1/notes/${noteId}`);
    
    const data = response.data;
    if (data.status) {
      ToastUtil(data.message || "删除笔记成功", "✅", "success");
      return true;
    } else {
      ToastUtil(data.message || "删除笔记失败", "❌", "error");
      return false;
    }
  } catch (error: any) {
    ToastUtil(error.message || "删除笔记异常", "❌", "error");
    return false;
  }
}